package com.hmdp.common.utils;

import cn.hutool.db.ds.simple.SimpleDataSource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @author WDs , wds8.24@outlook.com
 * @version 1.0
 * @since 2023-01-14 13:37
 */
@Component
public class RedisIdWorker {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final long startTime = 1640995200L;
    private static final int SNBits = 32;
    public long nextId(String keyPrefix) {
        LocalDateTime now = LocalDateTime.now();
        String dateStr = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        Long sn = stringRedisTemplate.opsForValue().increment(RedisConstants.INCR_PREFIX + keyPrefix + dateStr);
        assert sn != null;
        long result = nowSecond - startTime;
        result = result << SNBits;
        result += sn;
        return result;
    }

}
